package com.szholly.pro.watergas_server.ps.android.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.utils.util.JSONUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class SurfaceWaterService {
	private String token = "android_token";

	/**
	 * 获取地表水站数据
	 * 
	 * @param userID
	 * @return
	 * @throws Exception
	 */
	public String getSurfaceWaterData(String groupId) throws Exception {
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t1.* from BC_SITE_INFO t1 left join OPERATION_GROUP_STATION_ASSO t3 "
				+ " on t1.exp_no =t3.station_id where  t1.station_category='1' and t1.BUILD_STATUS='0'";
		if (null != groupId && !groupId.isEmpty()) {
			sql += " and t3.operation_group_id = @groupId ";
			parms.add(new GlobalParameter("groupId", groupId));
		}
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}
	/**
	 * android获取站点信息
	 * 
	 * @param userName
	 * @param password
	 * @return
	 * @throws Exception
	 */

	public String getSurfaceWaterStationInfo(String wwtp_id) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		if (wwtp_id == null && wwtp_id.equals("")) {
			return "";
		}
		String sql = "select t.EXP_NO as STATION_ID,t.FLOW_TYPE from BC_SITE_INFO t where wwtp_id ='" + wwtp_id
				+ "'";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}
	/**
	 * 根据事件Id获取地表水所有任务 因为时间关系 直接套用原来污水的东西
	 * 
	 * @param jobId
	 * @return
	 */

	public String getSurfaceTaskStatusById(String jobId, String station_id, String task_type) {
		checkToken(token);
		String result = "";
		if (task_type.equals("0")) {
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			// 所有任务语句
			String ProcessedSql = "select t1.task_code,t1.task_status,t3.name as station_name,t1.job_id,t3.name as name,"
					+ " to_char(t1.start_time,'yyyy-mm-dd hh24:mi:ss') as start_time,"
					+ " to_char(t1.end_time,'yyyy-mm-dd hh24:mi:ss') as end_time ,null as TASK_TOLERANCE, "
					+ " to_char(t1.FINISH_TIME,'yyyy-mm-dd hh24:mi:ss') as FINISH_TIME,t1.STATION_ID as exp_no from  OPERATION_TASK t1 "
					+ " left join OPERATION_GROUP_STATION_ASSO t2 on t1.WWTP_ID =t2.station_id"
					+ " left join BC_SITE_INFO t3 on t3.EXP_NO = t1.station_id where 1 = 1 ";
			if (jobId != null && !jobId.equals("")) {
				ProcessedSql += " and t1.JOB_ID =@jobId";
				parms.add(new GlobalParameter("jobId", jobId));
			}
			if (station_id != null && !station_id.equals("")) {
				ProcessedSql += " and t1.station_id  =@station_id";
				parms.add(new GlobalParameter("station_id", station_id));
			}
			List<RowBase> rowProcessed = DataUtil.getSelectRows(ProcessedSql, parms);
			JSONArray ProcessedData = new JSONArray();
			JSONArray PendingData = new JSONArray();
			JSONArray TimeoutHandlingData = new JSONArray();
			if (rowProcessed != null && rowProcessed.size() > 0) {
				for (int i = 0; i < rowProcessed.size(); i++) {
					HashMap<String, Object> d = rowProcessed.get(i);
					String task_status = d.get("TASK_STATUS").toString();
					Calendar deathCal = Calendar.getInstance();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String et = d.get("END_TIME").toString();// 截止时间
					// String st=d.get("START_TIME").toString();//开始时间
					Date et_date = new Date();
					// Date st_date=new Date();
					Date fishtime_date = new Date();
					Date nowdate = new Date();
					try {
						et_date = sdf.parse(et);
						// st_date=sdf.parse(st);
						deathCal.setTime(et_date);
					} catch (ParseException e) {

						e.printStackTrace();
					}
					int timeCycleNum = 0;
					if (null != d.get("TASK_TOLERANCE")) {
						timeCycleNum = Integer.parseInt(d.get("TASK_TOLERANCE").toString().replaceAll("[a-zA-Z]", ""));
						if (d.get("TASK_TOLERANCE").toString().indexOf("D") > 0) {
							deathCal.add(Calendar.DAY_OF_MONTH, timeCycleNum);
						} else if (d.get("TASK_TOLERANCE").toString().indexOf("M") > 0) {
							deathCal.add(Calendar.MONTH, timeCycleNum);
						}
					}

					Date truefishtime = deathCal.getTime();

					if (task_status.equals("0")) {// 未处理
						// if (truefishtime.getTime() >= nowdate.getTime()) {
						PendingData.add(d);
						// } else {
						// TimeoutHandlingData.add(d);
						// }
					}
					if (task_status.equals("1")) {// 已处理
						String fishtime = d.get("FINISH_TIME").toString();// 完成时间
						try {
							fishtime_date = sdf.parse(fishtime);
						} catch (ParseException e) {

							e.printStackTrace();
						}
						ProcessedData.add(d);
						// 暂时屏蔽，不做超时判断
						/*
						 * if(fishtime_date.getTime()>=truefishtime.getTime()){
						 * ProcessedData.add(d); } else{
						 * TimeoutHandlingData.add(d); }
						 */
					}
				}
			}

			JSONObject jsobj = new JSONObject();
			jsobj.put("PendingData", PendingData);
			jsobj.put("ProcessedData", ProcessedData);
			jsobj.put("TimeoutHandlingData", TimeoutHandlingData);
			List<JSONObject> allData = new ArrayList<>();
			allData.add(jsobj);
			String result1 = JSONUtils.toJSONString(allData);
			return JSONUtils.toJSONString(result1);
		}
		if (task_type.equals("1")) {
			result = getAbnormalDisposalData(jobId, station_id, "");
		}
		return result;

	}
	/**
	 * 获取异常处置数据
	 * 
	 * @param jobId
	 * @param station_id
	 * @param flowType
	 * @param status
	 * @return
	 */
	private String getAbnormalDisposalData(String jobId, String station_id, String flowType) {
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		// String sql="select t1.* from OP_ALAR_INFO t1 left join
		// monitor_station t2 on t1.station_code = t2.exp_no where 1 = 1 ";

		String sql = "select * from (select t1.guid, t1.type,t1.alarm_value,t1.station_code,t1.status,'a' as fish_type,to_char((t1.createtime+1),'yyyy-mm-dd hh24:mi:ss')  "
				+ "as END_TIME,to_char((t1.createtime),'yyyy-mm-dd hh24:mi:ss')  as START_TIME,'123456' as job_id,d1.s_domaincaption as type_desc "
				+ "from OP_ALAR_INFO t1 " + "left join BC_SITE_INFO t2  on t1.station_code = t2.exp_no  "
				+ "left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = '报警类型' AND d1.S_DOMAINCODE = t1.type )\n"
				+ "where  t1.status = '0' and t1.is_recover='0' and t1.station_code='" + station_id
				+ "' order by t1.start_time desc)t where rownum < 11 \n" + "union all\n"
				+ "select * from (select t1.guid, t1.type,t1.alarm_value,t1.station_code,t1.status,'b' as fish_type,to_char((t1.createtime+1),'yyyy-mm-dd')  as END_TIME"
				+ ",to_char((t1.createtime),'yyyy-mm-dd')  as START_TIME,'123456' as job_id,d1.s_domaincaption as type_desc"
				+ " from OP_ALAR_INFO t1 " + "left join BC_SITE_INFO t2  on t1.station_code = t2.exp_no"
				+ " left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = '报警类型' AND d1.S_DOMAINCODE = t1.type )\n"
				+ "left join OP_ALAR_PROC t3 on t1.guid=t3.alarm_id\n"
				+ "where  t1.status = '1' and (t3.end_time-t1.createtime)  < 1 and t1.station_code='" + station_id
				+ "' order by t1.start_time desc)t where rownum < 11\n" + "union all\n"
				+ "select * from (select t1.guid, t1.type,t1.alarm_value,t1.station_code,t1.status,'c' as fish_type,to_char((t1.createtime+1),'yyyy-mm-dd')  as END_TIME,to_char((t1.createtime),'yyyy-mm-dd')  as START_TIME,'123456' as job_id,d1.s_domaincaption as type_desc from OP_ALAR_INFO t1 left join BC_SITE_INFO t2  on t1.station_code = t2.exp_no left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = '报警类型' AND d1.S_DOMAINCODE = t1.type )\n"
				+ "left join OP_ALAR_PROC t3 on t1.guid=t3.alarm_id\n"
				+ "where  t1.status = '1' and (t3.end_time-t1.createtime)  >1 and t1.station_code='" + station_id
				+ "' order by t1.start_time desc)t where rownum < 11";
		/*
		 * if(station_id != null && !station_id.equals("")){ sql+=
		 * " and t1.station_code =@station_code"; parms.add(new
		 * GlobalParameter("station_code",station_id)); } if(status != null &&
		 * !status.equals("")){ sql+=" and t1.STATUS =@status"; parms.add(new
		 * GlobalParameter("status",status)); }
		 */
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		JSONArray ProcessedData = new JSONArray();// 正常时间已处理
		JSONArray PendingData = new JSONArray();// 待处理
		JSONArray TimeoutHandlingData = new JSONArray();// 超时已处理
		if (rows != null && rows.size() > 0) {
			for (int i = 0; i < rows.size(); i++) {
				HashMap<String, Object> d = rows.get(i);
				String FISH_TYPE = d.get("FISH_TYPE").toString();
				if (FISH_TYPE.equals("a")) {// 待处理
					PendingData.add(d);
				}
				if (FISH_TYPE.equals("b")) {// 已处理
					ProcessedData.add(d);
				}
				if (FISH_TYPE.equals("c")) {// 待处理
					TimeoutHandlingData.add(d);
				}
			}
			JSONObject jsobj = new JSONObject();
			jsobj.put("PendingData", PendingData);
			jsobj.put("ProcessedData", ProcessedData);
			jsobj.put("TimeoutHandlingData", TimeoutHandlingData);
			List<JSONObject> allData = new ArrayList<>();
			allData.add(jsobj);
			String result = JSONUtils.toJSONString(allData);
			return JSONUtils.toJSONString(result);
		} else {
			return "";
		}
	}
	/**
	 * 根据地表水站点获取在线设备
	 * 
	 * @param flow_type
	 * @param wwtp_id
	 * @return
	 */
	public String getSurfaceEquipmentByStation(String wwtp_id) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t1.name,t1.DEVICE_TYPENUM,t1.DEVICE_NUM from BC_SITE_DEVICE_RPT t1 "
				+ "left join BC_SITE_INFO t2 on t1.monitor_point=t2.exp_no where 1=1 ";
		if (wwtp_id != null && !wwtp_id.equals("")) {
			sql += " and t2.exp_no =@wwtp_id";
			parms.add(new GlobalParameter("wwtp_id", wwtp_id));
		}
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}

	private void checkToken(String token) {
		if (!ObjectUtils.equals(token, this.token)) {
			throw new RuntimeException("认证错误！");
		}
	}

	static boolean checkNull(String date) {
		if (null == date || date.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}
}
